<!--
  文件级注释：分账协议详情页面
  - 展示协议基础信息
  - 管理分账参与方（新增、删除、确认）
  - 绑定收款码到该协议
  规则：返回值 code === 0 视为成功
-->

<template>
  <div class="container">
    <div class="header">
      <h1>分账协议详情</h1>
      <router-link class="btn" to="/divided-agreements">返回列表</router-link>
    </div>

    <!-- 协议基础信息（统一使用 camelCase 展示，避免后端大小写差异导致无法渲染） -->
    <div class="card">
      <div class="row"><span class="label">协议ID：</span><span>{{ base?.id || '-' }}</span></div>
      <div class="row"><span class="label">协议名称：</span><span>{{ base?.agreementName || '-' }}</span></div>
      <div class="row"><span class="label">协议编码：</span><span>{{ base?.agreementCode || '-' }}</span></div>
      <div class="row"><span class="label">启用状态：</span><span>{{ formatEnable(base?.enableStatus) }}</span></div>
      <div class="row"><span class="label">激活状态：</span><span>{{ formatActivation(base?.activationStatus) }}</span></div>
      <div class="row"><span class="label">分账周期：</span><span>{{ base?.dividedCycle ?? '-' }}</span></div>
      <div class="row"><span class="label">创建时间：</span><span>{{ base?.creationTime || '-' }}</span></div>
    </div>

    <!-- 参与方管理 -->
    <div class="section">
      <div class="section-header">
        <h2>参与方</h2>
        <button class="btn primary" @click="openAddDetail">新增参与方</button>
      </div>
      <table class="table">
        <thead>
          <tr>
            <th>参与角色ID</th>
            <th>用户ID</th>
            <th>用户名</th>
            <th>手机号</th>
            <th>分账比例</th>
            <th>是否主账号</th>
            <th>创建时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="d in details" :key="d.id">
            <td>{{ d.userRoleId || '-' }}</td>
            <td>{{ d.userId || '-' }}</td>
            <td>{{ d.userName || '-' }}</td>
            <td>{{ d.userPhone || '-' }}</td>
            <td>{{ d.ratio ?? '-' }}</td>
            <td>{{ d.isMasterAccount ? '是' : '否' }}</td>
            <td>{{ d.creationTime || '-' }}</td>
            <td>
              <button class="link" @click="onConfirmDetail(d.id, d.userPhone)">确认</button>
              <button class="link danger" @click="onDeleteDetail(d.id)">删除</button>
            </td>
          </tr>
          <tr v-if="details.length === 0"><td colspan="8" class="empty">暂无参与方</td></tr>
        </tbody>
      </table>
    </div>

    <!-- 收款码绑定 -->
    <div class="section">
      <div class="section-header">
        <h2>绑定收款码</h2>
        <div class="bind-bar">
          <input v-model="bindCodeId" class="input" placeholder="收款码ID" />
          <button class="btn" @click="onBindCodes">绑定</button>
        </div>
      </div>
      <div class="tips">支持绑定多个收款码，按需重复绑定。</div>
      <div class="sub-section">
        <div class="section-header">
          <h3>已绑定收款码</h3>
          <div>
            <button class="btn" @click="onRefreshBoundCodes">刷新列表</button>
          </div>
        </div>
        <table class="table">
          <thead>
            <tr>
              <th>收款码ID</th>
              <th>名称</th>
              <th>码值</th>
              <th>门店</th>
              <th>启用状态</th>
              <th>创建时间</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="c in boundCodes" :key="c.id">
              <td>
                <router-link class="link" :to="`/payment-codes/detail/${c.id}`">{{ c.id || '-' }}</router-link>
              </td>
              <td>{{ c.codeName || '-' }}</td>
              <td>{{ c.code || '-' }}</td>
              <td>{{ c.storeName || '-' }}</td>
              <td>{{ formatEnable(c.enableStatus) }}</td>
              <td>{{ c.creationTime || '-' }}</td>
              <td>
                <router-link class="link" :to="`/payment-codes/detail/${c.id}`">查看</router-link>
                <button class="link danger" @click="onUnbindCode(c.id)">解绑</button>
              </td>
            </tr>
            <tr v-if="boundCodes.length === 0"><td colspan="7" class="empty">暂无绑定</td></tr>
          </tbody>
        </table>
      </div>
    </div>

    <!-- 新增参与方弹窗 -->
    <div v-if="addDetail.open" class="modal">
      <div class="modal-content">
        <h3>新增参与方</h3>
        <div class="form">
          <label>
            用户ID：
            <input v-model="addDetail.form.UserId" class="input" placeholder="请输入用户ID" />
          </label>
          <label>
            分账比例（数值）：
            <input v-model.number="addDetail.form.Ratio" class="input" type="number" min="0" step="0.01" />
          </label>
          <label>
            角色ID（可选）：
            <input v-model="addDetail.form.UserRoleId" class="input" placeholder="按需填写角色ID" />
          </label>
        </div>
        <div class="modal-actions">
          <button class="btn" @click="closeAddDetail">取消</button>
          <button class="btn primary" @click="onAddDetail">确认新增</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { useRoute } from 'vue-router'
import { DividedService } from '../services/divided'
import { isSuccess } from '../services/types'
import { PaymentCodeService } from '../services/paymentCode'

/** 组件级注释：展示分账协议详情并进行相关管理操作 */

const route = useRoute()
/** 协议ID */
const agreementId = ref<string>(String(route.params.id || route.path.split('/').pop() || ''))

/** 基础信息 */
const base = ref<any | null>(null)
/** 参与方列表 */
const details = ref<any[]>([])
/** 绑定的收款码ID */
const bindCodeId = ref('')
/** 已绑定收款码详情列表（用于增强展示与操作） */
const boundCodes = ref<any[]>([])

/** 新增参与方弹窗 */
const addDetail = ref({
  open: false,
  form: {
    UserId: '',
    Ratio: undefined as number | undefined,
    UserRoleId: ''
  }
})

/**
 * 函数级注释：获取协议基础信息
 * @returns Promise<void>
 * @throws 可能抛出网络异常
 */
async function fetchBase(): Promise<void> {
  const res = await DividedService.getDividedAgreement(agreementId.value)
  if (isSuccess(res)) {
    // 兼容后端大小写差异，统一为 camelCase，确保页面可正确渲染
    const d: any = res.data || {}
    base.value = {
      id: d.Id ?? d.id ?? '',
      agreementName: d.AgreementName ?? d.agreementName ?? '',
      agreementCode: d.AgreementCode ?? d.agreementCode ?? '',
      enableStatus: d.EnableStatus ?? d.enableStatus ?? undefined,
      activationStatus: d.ActivationStatus ?? d.activationStatus ?? undefined,
      dividedCycle: d.DividedCycle ?? d.dividedCycle ?? undefined,
      creationTime: d.CreationTime ?? d.creationTime ?? '',
      merchantId: d.MerchantId ?? d.merchantId ?? '',
      parentAgreementId: d.ParentAgreementId ?? d.parentAgreementId ?? null,
      codeIds: Array.isArray(d.CodeIds) ? d.CodeIds : Array.isArray(d.codeIds) ? d.codeIds : []
    }
    // 刷新绑定收款码详情
    await fetchBoundCodeDetails()
  } else {
    alert(res.message || '获取协议信息失败')
  }
}

/**
 * 函数级注释：获取协议参与方列表
 * @returns Promise<void>
 * @throws 可能抛出网络异常
 */
async function fetchDetails(): Promise<void> {
  const res = await DividedService.getDividedAgreementDetailList(agreementId.value)
  if (isSuccess(res)) {
    // 兼容后端大小写差异，统一为 camelCase
    const arr: any[] = Array.isArray(res.data) ? res.data : []
    details.value = arr.map((d: any) => ({
      id: d.Id ?? d.id ?? '',
      dividedAgreementId: d.DividedAgreementId ?? d.dividedAgreementId ?? '',
      userId: d.UserId ?? d.userId ?? '',
      userName: d.UserName ?? d.userName ?? d.Name ?? d.name ?? '',
      userPhone: d.UserPhone ?? d.userPhone ?? '',
      ratio: d.Ratio ?? d.ratio ?? undefined,
      userRoleId: d.UserRoleId ?? d.userRoleId ?? '',
      isMasterAccount: d.IsMasterAccount ?? d.isMasterAccount ?? false,
      creationTime: d.CreationTime ?? d.creationTime ?? ''
    }))
  } else {
    alert(res.message || '获取参与方失败')
  }
}

/**
 * 函数级注释：打开新增参与方弹窗
 */
function openAddDetail(): void { addDetail.value.open = true }
/** 关闭新增参与方弹窗 */
function closeAddDetail(): void { addDetail.value.open = false }

/**
 * 函数级注释：新增参与方
 * @returns Promise<void>
 */
async function onAddDetail(): Promise<void> {
  const payload = { DividedAgreementId: agreementId.value, ...addDetail.value.form }
  if (!payload.UserId) { alert('请填写用户ID'); return }
  const res = await DividedService.addDividedAgreementDetail(payload as any)
  if (isSuccess(res)) {
    alert('新增成功')
    closeAddDetail()
    fetchDetails()
  } else {
    alert(res.message || '新增失败')
  }
}

/**
 * 函数级注释：删除参与方
 * @param id 详情ID
 * @returns Promise<void>
 */
async function onDeleteDetail(id?: string): Promise<void> {
  if (!id) return
  if (!confirm('确认删除该参与方吗？')) return
  const res = await DividedService.deleteDividedAgreementDetail([id])
  if (isSuccess(res)) {
    alert('删除成功')
    fetchDetails()
  } else {
    alert(res.message || '删除失败')
  }
}

/**
 * 函数级注释：确认参与方信息
 * @param id 详情ID
 * @returns Promise<void>
 */
/**
 * 函数级注释：确认参与方信息
 * @param id 详情ID
 * @param phone 参与方手机号（用于后端校验，必填）
 * @returns Promise<void>
 * @throws 可能抛出网络异常
 */
async function onConfirmDetail(id?: string, phone?: string): Promise<void> {
  if (!id) return
  const inputPhone = phone || prompt('请输入参与方手机号用于确认：') || ''
  if (!inputPhone) { alert('手机号不能为空'); return }
  const res = await DividedService.confirmDividedAgreementDetail(id, inputPhone)
  if (isSuccess(res)) {
    alert('已确认')
    fetchDetails()
  } else {
    alert(res.message || '确认失败')
  }
}

/**
 * 函数级注释：绑定收款码到协议
 * @returns Promise<void>
 */
async function onBindCodes(): Promise<void> {
  if (!bindCodeId.value) { alert('请输入收款码ID'); return }
  // 并集更新：避免覆盖已有绑定
  const existing = Array.isArray(base.value?.codeIds) ? base.value!.codeIds : []
  const union = Array.from(new Set([...(existing || []), bindCodeId.value]))
  const res = await DividedService.setDividedAgreementPaymentCodes({ DividedAgreementId: agreementId.value, PaymentCodeIds: union })
  if (isSuccess(res)) {
    alert('绑定成功')
    bindCodeId.value = ''
    // 重新刷新基础信息，确保已绑定收款码列表实时更新
    await fetchBase()
    await fetchBoundCodeDetails()
  } else {
    alert(res.message || '绑定失败')
  }
}

/**
 * 函数级注释：拉取已绑定收款码的详情列表并渲染
 * @returns Promise<void>
 * @throws 可能抛出网络异常
 */
async function fetchBoundCodeDetails(): Promise<void> {
  const ids: string[] = Array.isArray(base.value?.codeIds) ? base.value!.codeIds : []
  if (!ids || ids.length === 0) { boundCodes.value = []; return }
  const tasks = ids.map(id => PaymentCodeService.getPaymentCodeDetail({ id }))
  const results = await Promise.allSettled(tasks)
  const list: any[] = []
  for (const r of results) {
    if (r.status === 'fulfilled' && isSuccess(r.value)) {
      const d: any = r.value.data || {}
      list.push({
        id: d.Id ?? d.id ?? '',
        code: d.Code ?? d.code ?? '',
        codeName: d.CodeName ?? d.codeName ?? '',
        codeUrl: d.CodeUrl ?? d.codeUrl ?? '',
        creationTime: d.CreationTime ?? d.creationTime ?? '',
        enableStatus: d.EnableStatus ?? d.enableStatus ?? undefined,
        merchantId: d.MerchantId ?? d.merchantId ?? '',
        storeId: d.StoreId ?? d.storeId ?? '',
        storeName: d.StoreName ?? d.storeName ?? '',
        parentId: d.ParentId ?? d.parentId ?? ''
      })
    }
  }
  boundCodes.value = list
}

/**
 * 函数级注释：解绑单个收款码并刷新绑定列表
 * @param codeId 收款码ID
 * @returns Promise<void>
 * @throws 可能抛出网络异常
 */
async function onUnbindCode(codeId?: string): Promise<void> {
  if (!codeId) return
  if (!confirm('确认解绑该收款码吗？')) return
  const existing = Array.isArray(base.value?.codeIds) ? base.value!.codeIds : []
  const next = (existing || []).filter((id: string) => id !== codeId)
  const res = await DividedService.setDividedAgreementPaymentCodes({ DividedAgreementId: agreementId.value, PaymentCodeIds: next })
  if (isSuccess(res)) {
    alert('已解绑')
    await fetchBase()
    await fetchBoundCodeDetails()
  } else {
    alert(res.message || '解绑失败')
  }
}

/**
 * 函数级注释：手动刷新已绑定收款码详情列表
 * @returns Promise<void>
 */
async function onRefreshBoundCodes(): Promise<void> {
  await fetchBoundCodeDetails()
}

/**
 * 函数级注释：格式化启用状态
 * @param s 启用状态
 * @returns string 可读文案
 */
function formatEnable(s?: number): string { return s === 1 ? '启用' : s === 0 ? '禁用' : '-' }
/**
 * 函数级注释：格式化激活状态
 * @param s 激活状态
 * @returns string 可读文案
 */
function formatActivation(s?: number): string { return s === 1 ? '已激活' : s === 0 ? '未激活' : '-' }
/**
 * 函数级注释：格式化角色ID（若后续接入角色字典可替换为名称）
 * @param r 角色ID
 * @returns string 可读文案
 */
function formatRoleId(r?: number | string): string { return String(r || '-') }

onMounted(async () => {
  await fetchBase()
  await fetchDetails()
  await fetchBoundCodeDetails()
})
</script>

<style scoped>
.container { display: grid; gap: 16px; }
.header { display: flex; justify-content: space-between; align-items: center; }
.btn { height: 32px; padding: 0 12px; border: 1px solid var(--border); background: var(--bg-secondary); border-radius: 6px; cursor: pointer; }
.btn.primary { background: var(--primary-50); color: var(--primary-700); border-color: var(--primary-200); }
.card { display: grid; gap: 8px; padding: 12px; border: 1px solid var(--border); border-radius: 8px; background: var(--card-bg); }
.row { display: flex; gap: 12px; }
.label { color: var(--text-secondary); width: 120px; }
.section { display: grid; gap: 8px; }
.section-header { display: flex; justify-content: space-between; align-items: center; }
.table { width: 100%; border-collapse: collapse; }
.table th, .table td { padding: 10px; border-bottom: 1px solid var(--border); text-align: left; }
.empty { text-align: center; color: var(--text-secondary); }
.bind-bar { display: flex; gap: 8px; align-items: center; }
.input { height: 32px; padding: 0 8px; border: 1px solid var(--border); border-radius: 6px; }
.modal { position: fixed; inset: 0; background: rgba(0,0,0,0.3); display: grid; place-items: center; }
.modal-content { width: 520px; background: var(--card-bg); border: 1px solid var(--border); border-radius: 8px; padding: 16px; display: grid; gap: 12px; }
.form { display: grid; gap: 8px; }
.modal-actions { display: flex; justify-content: flex-end; gap: 8px; }
.link { background: none; border: none; color: var(--primary-700); cursor: pointer; margin-right: 8px; }
.link.danger { color: #d23c3c; }
</style>
